﻿using MediatR;
using MediatR_.MediatR_Notifications;
using MediatR_.MediatR_Request;
using MediatR_.MediatR_RequestStream;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;

namespace 日志的使用.Controllers
{ 
    /// <summary>
    /// 使用MediatR
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class MediatRController : ControllerBase
    {
        private readonly IMediator mediator;

        public MediatRController(IMediator mediator)
        {
            this.mediator = mediator;
        }

        [HttpGet]
        public async Task<ActionResult<object>> GetMediatRQuest(CancellationToken token)
        {
            var valueStr = await mediator.Send(new Ping(),token);
            return valueStr;
        }
        [HttpGet]
        public async Task<ActionResult> GetMediatRStream(CancellationToken token)
        {
            CancellationTokenSource cts = new();
            int count = 10;
            List<int> mylist = new();
            //注意流使用的是CreateStream
            await foreach (var item in mediator.CreateStream<int>(new CounterStreamRequest(),cts.Token))
            {
                count--;
                if (count == 0)
                {
                  cts.Cancel();
                }
                mylist.Add(item);
            }
            return  new JsonResult(mylist);
        }

        /// <summary>
        /// MediatR 发布-订阅
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> GetMediatRNotifiy() 
        {
            await mediator.Publish(new Notifiy());
            return new OkResult();
        }
    }
}
